/**
 * 统计数据相关
 * @authors 杨兴洲（of2502）
 * @date    2017/3/28 10:55
 * @version 1.0
 */

import {Router} from "express";
import UserService from "../../service/user-service";
import WxStatistic from "../../service/weixin-statistic-service";
import MessageService from "../../service/message-service";

const router = Router();

/**
 * 基本数据
 */
router.get('/', (req, res, next) => {
    (async () => {
        try {
            const {userID} = res.locals;
            const {begin_date, end_date} = req.query;
            const access_token = await UserService.getAccessToken(userID);

            const params = {access_token, begin_date, end_date};
            const userChangeData = await WxStatistic.getUserSummary(params);
            const userTotalData = await WxStatistic.getUserCumulate(params);
            const msgTotalData = await WxStatistic.getMsgData(params);
            const {authorizer_appid: appID} = await UserService.getInfo(userID);

            // todo: 等待优化
            // summaryUser,cumulateMsg 日期数据不全，或者重复
            // cumulateUser 数据是全的
            const getAllData = async (item) => {
                const {ref_date, cumulate_user} = item;
                const currentUserChangeData = userChangeData.filter(item => item.ref_date === ref_date);
                const currentMsgTotalData = msgTotalData.filter(item => item.ref_date === ref_date);
                const calcTotal = (obj, prop) => obj.reduce((prev, cur) => cur[prop] + prev, 0);// 累加属性值
                const {count: msg_send_count} = await MessageService.getSendCount({
                    appID,
                    msgType: "all",
                    beginDate: ref_date,
                    endDate: ref_date
                });
                return {
                    [ref_date]: {
                        cumulate_user,
                        new_user: calcTotal(currentUserChangeData, "new_user"),
                        cancel_user: calcTotal(currentUserChangeData, "cancel_user"),
                        msg_count: calcTotal(currentMsgTotalData, "msg_count"),
                        msg_user: calcTotal(currentMsgTotalData, "msg_user"),
                        msg_send_count
                    }
                }
            };
            let result = await Promise.all(userTotalData.map(getAllData));
            res.status(200).json(result);
        } catch (error) {
            next(error);
        }
    })();
});

export default router;
